#include "phonebook.hpp"
#include <algorithm>
#include <iomanip> // 用于 std::setw 和 std::left
#include <iostream>

void PhoneBook::initializePhoneBook() { contacts.clear(); }


void PhoneBook::addContact() {
	if (contacts.size() < 100) {
		std::string name, phone;
		std::cout << "请输入联系人信息\n";
		std::cout << "-> 姓名: ";
		std::getline(std::cin, name); // 使用 getline，避免只输入第一个词
		std::cout << "-> 电话: ";
		std::getline(std::cin, phone);
		contacts.push_back(Contact(std::move(name), std::move(phone)));
		std::cout << "✅ 添加成功.\n";
	} else {
		std::cout << "⛔ 通讯录已满, 无法继续.\n";
	}
}

void PhoneBook::searchContact() const {
	std::string name;
	bool found = false;
	std::cout << "请输入姓名: ";
	std::getline(std::cin, name);

	for (const auto &contact: contacts) {
		if (contact.name == name) {
			std::cout << "姓名: " << contact.name << " \t 电话: " << contact.phone << "\n";
			found = true;
			break;
		}
	}

	if (!found) {
		std::cout << "⛔ 未找到该联系人.\n";
	}
}

void PhoneBook::displayContacts() const {
	if (contacts.empty()) {
		std::cout << "⛔ 通讯录为空.\n";
		return;
	}

	for (size_t i = 0; i < contacts.size(); ++i) {
		std::cout << i + 1 << ". 姓名: " << contacts[i].name << " \t电话: " << contacts[i].phone << "\n";
	}
}

void PhoneBook::deleteContact() {
	std::string name;
	std::cout << "请输入要删除的联系人姓名: ";
	std::getline(std::cin, name);

	auto it = std::find_if(contacts.begin(), contacts.end(), [&name](const Contact &c) { return c.name == name; });

	if (it != contacts.end()) {
		contacts.erase(it);
		std::cout << "✅ 已删除联系人: " << name << "\n";
	} else {
		std::cout << "⛔ 未找到该联系人，删除失败.\n";
	}
}

void PhoneBook::printMenu() {
	std::printf("+------- 通讯录 --------+\n");
	std::printf("| %-3d | %-4s \t|\n", 1, "添加联系人");
	std::printf("| %-3d | %-4s \t|\n", 2, "搜索联系人");
	std::printf("| %-3d | %-4s \t|\n", 3, "全部联系人");
	std::printf("| %-3d | %-4s \t|\n", 4, "删除联系人");
	std::printf("| %-3d | %-4s \t|\n", 5, "退出程序");
	std::printf("+-----------------------+\n");
}
